//
//  OtherViewController.m
//  FNer
//
//  Created by 王展 on 15/9/28.
//  Copyright (c) 2015年 wangzhan. All rights reserved.
//

#import "OtherViewController.h"
#import "BaseCollectionView.h"
#import "MusicCollectionViewCell.h"
#import "Music.h"
#import "UINavigationController+animation.h"
//#import "Music.h"
#import "ReturnTime.h"
#import "MusicDetailViewController.h"
//#import "DataHandle.h"
#import "VedioTableViewCell.h"
#import "VideoDetailViewController.h"
#import "MJRefresh.h"
#import "Video.h"
#import "SearchMusicViewController.h"
#import "MusicPlayerViewController.h"
#import "MusicErchDetailModel.h"
@interface OtherViewController ()

@property(nonatomic,retain)UIScrollView *otherSV;

@property(nonatomic,retain)UIView *titleButtonView;//分区Button所在视图
@property(nonatomic,retain)UIImageView *buttonImageView;//分区按钮图
@property(nonatomic,retain)UIButton *allButton;//全部频道按钮
@property(nonatomic,retain)UIButton *myButton;//我的频道按钮
@property(nonatomic,retain)UIButton *lastButton;//记录上一个分区Button
@property (nonatomic,retain)NSString *dataStr;
@property(nonatomic,retain)BaseCollectionView *musicCV;
@property(nonatomic,retain)NSMutableArray *musicArray;
@property(nonatomic,assign)BOOL isupLoading;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,retain)UILabel *atitleLabel;

@property(nonatomic,retain)UITableView *videoTV;
@property(nonatomic,assign)BOOL UpLoading;
@property(nonatomic,retain)NSMutableArray *videoArray;

@property(nonatomic,retain)MusicCollectionViewCell *cell;

@end

@implementation OtherViewController

//页面将要显示时触发
-(void)viewWillAppear:(BOOL)animated
{
    [self.myAgent appearOhterBottomBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //初始化
    self.musicArray = [NSMutableArray array];
    self.isupLoading = NO;
    self.page = 1;
    self.UpLoading = NO;
    self.videoArray = [NSMutableArray array];
    
    self.atitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100 * XWIDTH, 10 * XHIGHT, 175 * XWIDTH, 30 * XHIGHT)];
    self.atitleLabel.backgroundColor = [UIColor colorWithRed:43 / 255.0 green:150 /255.0 blue:199 / 255.0 alpha:1];
    self.atitleLabel.layer.masksToBounds = YES;
    self.atitleLabel.layer.cornerRadius = 15 * XWIDTH;
    self.atitleLabel.text = @"  FNER           ";
    self.atitleLabel.font = [UIFont systemFontOfSize:15 * XWIDTH];
    self.atitleLabel.textAlignment = NSTextAlignmentCenter;
    self.atitleLabel.textColor = [UIColor whiteColor];
    self.atitleLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *alistTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabelAction)];
    [self.atitleLabel addGestureRecognizer:alistTap];
    
    //建立社区内分区按钮
    self.titleButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 180 * XWIDTH, 25 * XHIGHT)];
    self.titleButtonView.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = self.titleButtonView;
    self.buttonImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5 * XWIDTH, 0, 70 * XWIDTH, 25 * XHIGHT)];
    self.buttonImageView.image = [UIImage imageNamed:@"分区按钮下蓝条.png"];
    [self.titleButtonView addSubview:self.buttonImageView];
    self.allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.allButton.frame = CGRectMake(0, 0, 80 * XWIDTH, 25 * XHIGHT);
    [self.allButton setTitleColor:[UIColor blackColor] forState:0];
    [self.allButton setTitle:@"音乐频道" forState:0];
    [self.allButton addTarget:self action:@selector(allButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.allButton setTitleColor:[UIColor colorWithRed:50 / 255.0 green:140 /255.0 blue:200 / 255.0 alpha:1] forState:UIControlStateSelected];
    [self.allButton setTitleColor:[UIColor whiteColor] forState:0];
    [self.titleButtonView addSubview:self.allButton];
    self.allButton.selected = YES;
    self.lastButton = self.allButton;
    self.allButton.tag = 2000;
    self.allButton.titleLabel.font = [UIFont systemFontOfSize:17 * XWIDTH];
    self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.myButton.frame = CGRectMake(100 * XWIDTH, 0, 80 * XWIDTH, 25 * XHIGHT);
    [self.myButton setTitle:@"微视频道" forState:0];
    [self.myButton setTitleColor:[UIColor colorWithRed:50 / 255.0 green:140 /255.0 blue:200 / 255.0 alpha:1] forState:UIControlStateSelected];
    [self.myButton setTitleColor:[UIColor whiteColor] forState:0];
    [self.titleButtonView addSubview:self.myButton];
    [self.myButton addTarget:self action:@selector(allButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.myButton.tag = 2001;
    self.myButton.titleLabel.font = [UIFont systemFontOfSize:17 * XWIDTH];

    //改主题颜色
    NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"nighting"];
    if ([string isEqualToString:@"yes"]) {
#warning 改的颜色
        [self.myButton setTitleColor:[UIColor blackColor] forState:0];
        [self.allButton setTitleColor:[UIColor blackColor] forState:0];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColoring:) name:@"changeColoring" object:nil];
    
    
        //左侧按钮
        UIImage *leftImage = [UIImage imageNamed:@"搜索icon.png"];
        leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction)];
    
    
    //创建音乐页面
    [self createOtherSV];
    [self createMusicView];
    [self createVideoView];
    [self addHeaderRefresh];
    [self addFooterRefresh];
    [self addVideoHeaderRefresh];
    [self addVideofooterRefresh];
}
//titleLabelAction点击事件
-(void)titleLabelAction
{
    [self addHeaderRefresh];
}
//创建大SV页面
-(void)createOtherSV
{
    self.otherSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT)];
    self.otherSV.contentSize = CGSizeMake(2 * WIDTH, HIGHT);
    self.otherSV.backgroundColor = [UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1];
    self.otherSV.bounces = NO;
    self.otherSV.pagingEnabled = YES;
    self.otherSV.delegate = self;
    [self.view addSubview:self.otherSV];
}

//下拉刷新
-(void)addHeaderRefresh
{
    __block OtherViewController *vc = self;
    self.musicCV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        vc.page = 1;
        [vc getMusicData];
        vc.isupLoading = NO;
    }];

    [self.musicCV.header beginRefreshing];
}
//上拉刷新
-(void)addFooterRefresh
{
    __block OtherViewController *vc = self;
   self.musicCV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       vc.page = vc.page + 1;
       [vc getMusicData];
       vc.isupLoading = YES;
       
   }];

}

-(void)addVideoHeaderRefresh
{
    __block OtherViewController *vc = self;
    self.videoTV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSDate * senddate=[NSDate date];
        
        NSCalendar * cal=[NSCalendar currentCalendar];
        
        NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
        
        NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
        
        NSInteger year=[conponent year];
        
        NSInteger month=[conponent month];
        
        NSInteger day=[conponent day];
        
        self.dataStr = [NSString stringWithFormat:@"%ld%ld%ld",year,month,day];

        [vc getVideoData];
        vc.UpLoading = NO;
        
    }];
       [self.videoTV.header beginRefreshing];
}


-(void)addVideofooterRefresh
{
    __block OtherViewController *vc = self;
    
    
    NSDate * senddate=[NSDate date];
    
    NSCalendar * cal=[NSCalendar currentCalendar];
    
    NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger year=[conponent year];
    
    NSInteger month=[conponent month];
    
    __block NSInteger  day=[conponent day];

    
    
    self.videoTV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
      day = day-1;
       self.dataStr = [NSString stringWithFormat:@"%ld%ld%ld",year,month,day];

        [vc getVideoData];
   
  
        vc.UpLoading = YES;
    }];

//    [self.videoTV.header beginRefreshing];
}


//创建视频页面
-(void)createVideoView
{
    self.videoTV = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, 0, WIDTH, HIGHT - 64 - 49) style:UITableViewStylePlain];
    self.videoTV.delegate = self;
    self.videoTV.dataSource = self;
    self.videoTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.videoTV.backgroundColor = [UIColor colorWithRed:231 / 255.0 green:231 / 255.0 blue:231 / 255.0 alpha:1];
    [self.otherSV addSubview:self.videoTV];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
#warning 行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VedioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[VedioTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
//    cell.backgroundColor = [UIColor redColor];
    cell.aVideo = [self.videoArray objectAtIndex:indexPath.row];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200 * XHIGHT;
}
//点击tableview触发事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"row = %ld",indexPath.row);
    [self.videoTV deselectRowAtIndexPath:indexPath animated:YES];
    VideoDetailViewController *videoDetailVC = [[VideoDetailViewController alloc] init];
    [self.myAgent hideOtherBottomBar];
    videoDetailVC.hidesBottomBarWhenPushed = YES;
 //   [self.navigationController pushViewController:videoDetailVC animated:NO];
    [self.navigationController pushViewController:videoDetailVC animatedWithTransition:UIViewAnimationTransitionFlipFromLeft];
    videoDetailVC.page = self.videoArray.count;
    videoDetailVC.myrow = indexPath.row;
    videoDetailVC.videoArray = self.videoArray;
}

#warning 获取视频数据
//获取视频数据
-(void)getVideoData
{
    //打印当前日期
    NSDate * senddate=[NSDate date];
    
    NSCalendar * cal=[NSCalendar currentCalendar];
    
    NSUInteger unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
    
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    
    NSInteger year=[conponent year];
    
    NSInteger month=[conponent month];
    
    NSInteger day=[conponent day];
    
    NSString * nsDateString= [NSString stringWithFormat:@"%ld%ld%ld",year,month,day];
    NSLog(@"%@",nsDateString);
    
    NSString *url_str = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/feed?date=%@&num=1&udid=26ee977959524afcac77e383b6ad78c2e3663eba&vc=51&vn=1.6.1&deviceModel=LT29i&first_channel=eyepetizer_baidu_market&last_channel=eyepetizer_baidu_market",self.dataStr];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"PHPSESSID=qtur65hr4cg4d60amesrt5ndm6" forHTTPHeaderField:@"Cookie"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_str parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        
      
        if (self.UpLoading == NO) {
             [self.videoArray removeAllObjects];
        }

        NSMutableDictionary *bigDic = responseObject;
     //   [[DataHandle shareDataHandle] videoHuanCun:bigDic];
        NSMutableArray *bigArray = [bigDic objectForKey:@"dailyList"];
        NSMutableDictionary *middleDic = [bigArray firstObject];
        NSMutableArray *array = [middleDic objectForKey:@"videoList"];
        for (NSMutableDictionary *dic in array) {
            Video *aVideo = [[Video alloc] init];
            [aVideo setValuesForKeysWithDictionary:dic];
            aVideo.detail = [dic objectForKey:@"description"];
    
            [self.videoArray addObject:aVideo];
        }
        
        
        
        
        [self.videoTV.header endRefreshing];
        [self.videoTV.footer endRefreshing];
        [self.videoTV reloadData];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
        [self.videoArray removeAllObjects];
        NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentPaht = [array lastObject];
        NSString *huancunDicFilePath = [documentPaht stringByAppendingPathComponent:@"videoDic.plist"];
        NSMutableDictionary *bigDic = [NSKeyedUnarchiver unarchiveObjectWithFile:huancunDicFilePath];
        
        if (bigDic != nil) {
            
            NSMutableArray *bigArray = [bigDic objectForKey:@"dailyList"];
            NSMutableDictionary *middleDic = [bigArray firstObject];
            NSMutableArray *array = [middleDic objectForKey:@"videoList"];
            for (NSMutableDictionary *dic in array) {
                Video *aVideo = [[Video alloc] init];
                [aVideo setValuesForKeysWithDictionary:dic];
                aVideo.detail = [dic objectForKey:@"description"];
                
                [self.videoArray addObject:aVideo];
            }
            
        }
        else
        {
            NSLog(@"没有缓存");
        }

        
        [self.videoTV.header endRefreshing];
        [self.videoTV reloadData];
    }];

}

//创建音乐页面
-(void)createMusicView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(172 * XWIDTH, 210 * XHIGHT);
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 9 * XWIDTH, 9 * XHIGHT, 9 * XWIDTH);
    flowLayout.headerReferenceSize = CGSizeMake(375 * XWIDTH, 50 * XHIGHT);
    
    self.musicCV = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (667 * XHIGHT - 49 - 64)) collectionViewLayout:flowLayout];
    self.musicCV.delegate = self;
    self.musicCV.dataSource = self;
    [self.otherSV addSubview:self.musicCV];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.musicArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.musicCV registerClass:[MusicCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    self.cell.backgroundColor = [UIColor whiteColor];
    
    self.cell.amusic = [self.musicArray objectAtIndex:indexPath.row];
    
    
    
    return self.cell;
}
//头部区域内容
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    [self.musicCV registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];

    [reusableView addSubview:self.atitleLabel];
    
    return reusableView;
}

//获取MUSIC数据
-(void)getMusicData
{
    NSString *url_str = [NSString stringWithFormat:@"http://echosystem.kibey.com/sound/hot?page=%ld",self.page];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"PHPSESSID=qtur65hr4cg4d60amesrt5ndm6" forHTTPHeaderField:@"Cookie"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_str parameters:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        
        if (self.isupLoading == NO) {
            [self.musicArray removeAllObjects];
        }
        NSMutableDictionary *bigDic = responseObject;
        
      //  [[DataHandle shareDataHandle] OtherHuancun:bigDic];
        
        NSMutableDictionary *Dic = [bigDic objectForKey:@"result"];
        NSMutableArray *bigArray = [Dic objectForKey:@"data"];
        for (NSMutableDictionary *dic in bigArray) {
            Music *amusic = [[Music alloc] init];
            [amusic setValuesForKeysWithDictionary:dic];
            [self.musicArray addObject:amusic];
        }
        
        [self.musicCV.header endRefreshing];
        [self.musicCV.footer endRefreshing];
        [self.musicCV reloadData];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
        NSLog(@"没有网络");
        [self.musicArray removeAllObjects];
        NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentPaht = [array lastObject];
        NSString *huancunDicFilePath = [documentPaht stringByAppendingPathComponent:@"OtherDic.plist"];
        NSMutableDictionary *bigDic = [NSKeyedUnarchiver unarchiveObjectWithFile:huancunDicFilePath];
        
        if (bigDic != nil) {
            
            NSMutableDictionary *Dic = [bigDic objectForKey:@"result"];
            NSMutableArray *bigArray = [Dic objectForKey:@"data"];
            for (NSMutableDictionary *dic in bigArray) {
                Music *amusic = [[Music alloc] init];
                [amusic setValuesForKeysWithDictionary:dic];
                [self.musicArray addObject:amusic];
            }

        }
        else
        {
            NSLog(@"没有缓存");
        }
        [self.musicCV.header endRefreshing];
        [self.musicCV.footer endRefreshing];
        [self.musicCV reloadData];
    }];
}
//点击MUSIC触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    

    MusicPlayerViewController *play = [MusicPlayerViewController sharePlayerDataHandel];
    [SHAREDAPPDELE.myTB isHiddenTabBar:YES withViewController:play];
    play.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:play animated:NO];
    MusicErchDetailModel *model =[self.musicArray objectAtIndex:indexPath.row];
    play.song_id = [model.id integerValue];
    play.allMusicArray = self.musicArray;
    play.indexRow = indexPath.row;

}
//创建分区按钮
-(void)allButtonAction:(UIButton *)button
{
    self.lastButton.selected = NO;
    button.selected = YES;
    self.lastButton = button;
    self.otherSV.contentOffset = CGPointMake((button.tag - 2000) * WIDTH, 0);
    if (self.allButton == button) {
        NSLog(@"音乐频道");
        if ((self.buttonImageView.frame.origin.x - (100 + 5) * XWIDTH) < 1 && (self.buttonImageView.frame.origin.x - (100 + 5) * XWIDTH) > -1) {
            [UIView animateWithDuration:0.3 animations:^{
                
                CGRect tempRect = self.buttonImageView.frame;
                tempRect.origin.x -= 100 * XWIDTH;
                self.buttonImageView.frame = tempRect;
                
            } ];
        }
    }
    else if (self.myButton == button){
        NSLog(@"视频频道");
        if ((self.buttonImageView.frame.origin.x - 5 * XWIDTH) < 1 && (self.buttonImageView.frame.origin.x - 5 * XWIDTH) > -1) {
            [UIView animateWithDuration:0.3 animations:^{
                
                CGRect tempRect = self.buttonImageView.frame;
                tempRect.origin.x += 100 * XWIDTH;
                self.buttonImageView.frame = tempRect;
                
            } ];
        }
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.otherSV) {
        UIButton *clickButton = (UIButton *)[self.titleButtonView viewWithTag:self.otherSV.contentOffset.x / WIDTH + 2000];
        [self allButtonAction:clickButton];
    }
    
}

-(void)changeColoring:(NSNotification *)notification
{
#warning 改的颜色
    [self.myButton setTitleColor:[UIColor blackColor] forState:0];
    [self.allButton setTitleColor:[UIColor blackColor] forState:0];
    
    NSString *string = [notification object];
    if ([string isEqualToString:@"no"]) {
        
#warning 原有颜色
        [self.myButton setTitleColor:[UIColor whiteColor] forState:0];
        [self.allButton setTitleColor:[UIColor whiteColor] forState:0];
    }
    //保存当前状态值
    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"nighting"];
}

-(void)leftButtonAction
{
    SearchMusicViewController *searchMusicVC = [[SearchMusicViewController alloc] init];
    [self.myAgent hideOtherBottomBar];
    searchMusicVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchMusicVC animated:NO];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
